package info.rflow.util;

import info.rflow.RFlow;
import info.rflow.Utils;

import javax.swing.*;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.Arrays;
import java.util.ResourceBundle;


/**
 * Document me!
 *
 * @author Holger Brandl
 */
public class ExampleData {

    public static void installExampleData(RFlow rflow) {

        File userHome = Utils.getUserHome();
        File exDataDir = new File(userHome, "RFlow Examples");

        // do nothing if the directory is already present or it's not the first launch
        if (exDataDir.isDirectory() || Utils.getPrefs().getInt(Utils.PROP_STARTUP_COUNTER, 0) != 1)
            return;

        ResourceBundle rb = Utils.getRB();
        Object[] options = {rb.getString("ExampleData.addexdata"), rb.getString("UpdateChecker.discardupdate")};

        int status = JOptionPane.showOptionDialog(rflow,
                rb.getString("ExampleData.exampleswanted"),
                rb.getString("ExampleData.title"),
                JOptionPane.YES_NO_OPTION,
                JOptionPane.QUESTION_MESSAGE,
                new ScaleableIcon("icons/reset.png", 100, 90),
                options,  //the titles of buttons
                options[0]);     //do not use a custom Icon

        if (status == JOptionPane.NO_OPTION)
            return;

        exDataDir.mkdir();

        try {
            for (String fileName : Arrays.asList("iris-analysis.R")) {
                URL exDataFileURL = Utils.loadResource("examples/" + fileName);
                final File rFile = new File(exDataDir, fileName);
                Utils.copyStreamIntoFile(rFile, exDataFileURL.openStream());

                URL layoutFileURL = Utils.loadResource("examples/." + fileName + ".layout");
                final File layoutFile = new File(exDataDir, "." + fileName + ".layout");
                Utils.copyStreamIntoFile(layoutFile, layoutFileURL.openStream());

                // hide the layout file on windows
                if (Utils.isWindowsPlatform()) {
                    try {
                        Runtime.getRuntime().exec("attrib +H '" + layoutFile.getAbsolutePath() + "'");
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }

                // open the example workflow
                rflow.getSesMan().loadWorkflow(rFile);

            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
